package com.youlu.campus.admin.config;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.admin.auth.entity.exception.AuthErrorCode;
import com.youlu.campus.common.exception.ApiErrorCode;
import com.youlu.campus.common.base.RestResultBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.CharEncoding;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@Slf4j
public class CorsInterceptor extends HandlerInterceptorAdapter {
    @Value("#{'${auth.allowOrigin:}'.empty ? null : '${auth.allowOrigin:}'.split(',')}")
    private String[] allowOrigins;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        String host = req.getServerName();
        log.info(":>>> Host:{}", host);
        if (StringUtils.isBlank(host)) {
            log.error(":>>> Host:为空");
            return true;
        }
        for (String s : allowOrigins) {
            if (s.equals(host)) {
                log.info(":.>> Host 验证OK");
                return true;
            }
        }
        log.info(":.>> Host 验证NO");
        outJson(resp, AuthErrorCode.INVALID_REQUEST);
        return false;
    }

    public void outJson(ServletResponse response, ApiErrorCode errorCode) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding(CharEncoding.UTF_8);//设置编码
            response.setContentType("application/json; charset=utf-8");//设置返回类型
            out = response.getWriter();
            out.println(JSON.toJSONString(RestResultBuilder.builder().errorCode(errorCode).build()));//输出
        } catch (Exception e) {
            log.error("json out error:{}", e.getMessage());
        } finally {
            if (null != out) {
                out.flush();
                out.close();
            }
        }
    }
}
